package org.example.managementsystem.controller;

import org.example.managementsystem.model.MaterialPurchase;
import org.example.managementsystem.service.MaterialPurchaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 物料采购控制器
 */
@RestController
@RequestMapping("/api/material-purchase")
@CrossOrigin
public class MaterialPurchaseController {
    private final MaterialPurchaseService materialPurchaseService;

    @Autowired
    public MaterialPurchaseController(MaterialPurchaseService materialPurchaseService) {
        this.materialPurchaseService = materialPurchaseService;
    }

    /**
     * 获取所有物料采购申请
     */
    @GetMapping("/list")
    public ResponseEntity<List<MaterialPurchase>> getAllPurchaseApplications() {
        List<MaterialPurchase> applications = materialPurchaseService.getAllPurchaseApplications();
        return ResponseEntity.ok(applications);
    }

    /**
     * 根据ID获取物料采购申请
     */
    @GetMapping("/{id}")
    public ResponseEntity<MaterialPurchase> getPurchaseApplicationById(@PathVariable Long id) {
        MaterialPurchase application = materialPurchaseService.getPurchaseApplicationById(id);
        if (application == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(application);
    }

    /**
     * 获取指定申请人的物料采购申请
     */
    @GetMapping("/applicant/{applicantJobNumber}")
    public ResponseEntity<List<MaterialPurchase>> getPurchaseApplicationsByApplicant(@PathVariable String applicantJobNumber) {
        List<MaterialPurchase> applications = materialPurchaseService.getPurchaseApplicationsByApplicant(applicantJobNumber);
        return ResponseEntity.ok(applications);
    }

    @PostMapping
    public ResponseEntity<String> createMaterialPurchase(@RequestBody MaterialPurchase purchaseMaterial) {
        try {
            materialPurchaseService.createMaterialPurchase(purchaseMaterial);
            return ResponseEntity.ok("申请提交成功");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
        }
    }

    @PutMapping("/{id}")
    public ResponseEntity<String> updateMaterialPurchase(@PathVariable Long id, @RequestBody MaterialPurchase purchaseMaterial) {
        try {
            purchaseMaterial.setPurchaseId(id);
            materialPurchaseService.updatePurchaseApplication(purchaseMaterial);
            return ResponseEntity.ok("申请更新成功");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
        }
    }

    /**
     * 获取待审批的物料采购申请列表
     */
    @GetMapping("/approvals")
    public ResponseEntity<List<MaterialPurchase>> getPendingApprovals() {
        List<MaterialPurchase> pendingApprovals = materialPurchaseService.getPendingApprovals();
        return ResponseEntity.ok(pendingApprovals);
    }

    /**
     * 提交审批决定
     */
    @PostMapping("/approve")
    public ResponseEntity<Map<String, Object>> submitApproval(@RequestBody Map<String, Object> approvalData) {
        Map<String, Object> result = new HashMap<>();
        try {
            Long purchaseId = Long.valueOf(approvalData.get("purchaseId").toString());
            String status = approvalData.get("isApproved").toString();
            String reason = approvalData.get("approvalDescription") != null ? approvalData.get("approvalDescription").toString() : "";
            
            boolean isApproved = "true".equals(status);
            
            MaterialPurchase purchase = materialPurchaseService.submitApproval(purchaseId, isApproved, reason);
            
            result.put("success", true);
            result.put("message", isApproved ? "采购申请已批准" : "采购申请已拒绝");
            result.put("data", purchase);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "审批失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 审批物料采购申请（保留原有接口）
     */
    @PostMapping("/approve/{id}")
    public ResponseEntity<Map<String, Object>> approvePurchaseApplication(
            @PathVariable Long id,
            @RequestParam boolean approved,
            @RequestParam String approverId,
            @RequestParam String approverName,
            @RequestParam(required = false) String description) {

        Map<String, Object> result = new HashMap<>();
        try {
            MaterialPurchase purchase = materialPurchaseService.approvePurchaseApplication(
                    id, approved, approverId, approverName, description);

            result.put("success", true);
            result.put("message", approved ? "采购申请已批准" : "采购申请已拒绝");
            result.put("data", purchase);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "审批失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }
    /**
     * 修改物料采购申请
     */
    @PutMapping("/update")
    public ResponseEntity<Map<String, Object>> updatePurchaseApplication(@RequestBody MaterialPurchase purchase) {
        Map<String, Object> result = new HashMap<>();
        try {
            MaterialPurchase updatedPurchase = materialPurchaseService.updatePurchaseApplication(purchase);
            result.put("success", true);
            result.put("message", "采购申请修改成功");
            result.put("data", updatedPurchase);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "采购申请修改失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 撤销物料采购申请
     */
    @PostMapping("/cancel/{id}")
    public ResponseEntity<Map<String, Object>> cancelPurchaseApplication(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        try {
            materialPurchaseService.cancelPurchaseApplication(id);
            result.put("success", true);
            result.put("message", "采购申请已撤销");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "撤销失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 完成物料采购
     */
    @PostMapping("/complete/{id}")
    public ResponseEntity<Map<String, Object>> completePurchase(
            @PathVariable Long id,
            @RequestParam String purchaseDetails) {

        Map<String, Object> result = new HashMap<>();
        try {
            MaterialPurchase purchase = materialPurchaseService.completePurchase(id, purchaseDetails);
            result.put("success", true);
            result.put("message", "采购已完成");
            result.put("data", purchase);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "完成采购失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 获取物料采购统计数据
     */
    @GetMapping("/statistics")
    public ResponseEntity<Map<String, Object>> getPurchaseStatistics(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(required = false) String departmentId) {

        LocalDateTime startTime = null;
        LocalDateTime endTime = null;
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        if (startDate != null && !startDate.isEmpty()) {
            startTime = LocalDateTime.parse(startDate + " 00:00:00", formatter);
        }

        if (endDate != null && !endDate.isEmpty()) {
            endTime = LocalDateTime.parse(endDate + " 23:59:59", formatter);
        }

        Map<String, Object> statistics = materialPurchaseService.getPurchaseStatistics(startTime, endTime, departmentId);
        return ResponseEntity.ok(statistics);
    }
    /**
     * 删除物料采购申请
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deletePurchaseApplication(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        try {
            materialPurchaseService.deletePurchaseApplication(id);
            result.put("success", true);
            result.put("message", "采购申请删除成功");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "采购申请删除失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }
}